package com.cpi.cornpp.instructionsattachment.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;

import com.cpi.cornpp.instructionsattachment.exception.InstructionAttachmentException;
import com.cpi.cornpp.instructionsattachment.form.InstructionAttachmentForm;
import com.cpi.cornpp.instructionsattachment.service.InstructionAttachmentService;
import com.cpi.cornpp.instructionsattachment.view.InstructionAttachmentView;
import com.cpi.cornpp.instructionspurchases.service.InstructionPurchaseService;
import com.cpi.cornpp.instructionspurchases.view.InstructionPurchaseCreateView;
import com.cpi.cornpp.purchaseinstructiondetail.service.InstructionPurchaseDetailService;
import com.cpi.cornpp.purchaseinstructiondetail.view.InstructionPurchaseDetailView;
import com.cs.common.init.SystemParameterCollection;
import com.cs.common.init.beans.SystemParameterBean;
import com.cs.common.utils.FileExtensionUtils;
import com.cs.common.utils.NumberUtil;
import com.cs.common.utils.StringUtils;



public class InstructionAttachmentAction extends MappingDispatchAction{

	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$

	private final static String ERROR_MESSAGE = "ERROR_MESSAGE";//$NON-NLS-1$

	private static final String DEFAULT_FORWARD = "default";//$NON-NLS-1$
	
	private static final String PID_PARAM = "pid";
	
	private static final String SUCCESS_ADD_LABEL = "common.add.success";//$NON-NLS-1$
	
	private static final String SUCCESS_DELETE_LABEL = "common.delete.success";//$NON-NLS-1$
	
	private final static String MESSAGE = "MESSAGE";//$NON-NLS-1$

	private static final String READ_ONLY = "READ_ONLY";//$NON-NLS-1$

	private static final String INSTRUCTION_PURCHASE_STATUS_OPENED_ID = "INSTRUCTION_PURCHASE_STATUS_OPENED_ID";

	private static final String ATTACHMENT_FILE_NAME = "\"attachment;filename=";//$NON-NLS-1$

	private static final String EXCEL_FILE = "excelFile";//$NON-NLS-1$

	private static final String FILE_NOT_FOUND = "label.instructionattachment.not.found";
	
	private MessageResources messageResources = null;
	
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionAttachmentException
	 */
	public ActionForward list(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws InstructionAttachmentException{		
		InstructionAttachmentForm form = null;
		List attachments= null;
		HttpSession session = null;		
		String messageError = null;
		String pidParam = null;
		InstructionAttachmentService service = null;
		
		InstructionPurchaseDetailService instructionPurchaseDetailService = null;
		InstructionPurchaseDetailView instructionPurchaseDetailView = null;
		
		InstructionPurchaseService instructionPurchaseService = null;
		InstructionPurchaseCreateView instructionPurchaseCreateView = null;
		
		int purchaseInstructionDetailID;
		SystemParameterCollection systemParameterCollection = null;
		SystemParameterBean systemParameterBean = null;
		try {
			form = (InstructionAttachmentForm)actionForm;
			service = new InstructionAttachmentService();
			instructionPurchaseDetailService = new InstructionPurchaseDetailService();
			instructionPurchaseService = new InstructionPurchaseService();
			messageResources = getResources(request);
			session = request.getSession(true);
			
			systemParameterCollection = SystemParameterCollection.getInstance();
			systemParameterBean = systemParameterCollection.getSystemParameterBean(INSTRUCTION_PURCHASE_STATUS_OPENED_ID);
			
			pidParam = request.getParameter(PID_PARAM);
			if( pidParam != null ){
				session.setAttribute(PID_PARAM, pidParam);
			}else{
				pidParam = (String)session.getAttribute(PID_PARAM);
			}
			purchaseInstructionDetailID = NumberUtil.parseInt(pidParam);
			attachments = (ArrayList)service.list(purchaseInstructionDetailID);
			instructionPurchaseDetailView = instructionPurchaseDetailService.getById(purchaseInstructionDetailID);
			instructionPurchaseCreateView = instructionPurchaseService.getInstructionPurchase(instructionPurchaseDetailView.getPurchaseInstructionId());
			if( instructionPurchaseCreateView.getPurchaseStatus() != systemParameterBean.getIntValue() ){
				request.setAttribute(READ_ONLY, String.valueOf(true));
			}else{
				request.setAttribute(READ_ONLY, String.valueOf(false));
			}
			form.setAttachments(attachments);
		} catch(InstructionAttachmentException ife){
			messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), ife.getErrorCode());
			
			if(null == messageError){
				InstructionAttachmentException ifee = new InstructionAttachmentException(ife, InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);
				session.setAttribute(CUSTOM_EXCEPTION, ifee);
				//form.reset(mapping, request);
				throw ifee;
			}else{
				session.setAttribute(ERROR_MESSAGE, messageError);				
			}
		} catch(Exception e){
			InstructionAttachmentException ppe = new InstructionAttachmentException(e , InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);;			
			session.setAttribute(CUSTOM_EXCEPTION, ppe);
			
			e.printStackTrace(System.out);
			
			throw ppe;
		}		
		return mapping.findForward(DEFAULT_FORWARD);		
	}
	
	public ActionForward newAttachment(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws InstructionAttachmentException{
		return mapping.findForward(DEFAULT_FORWARD);
	}
	
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionAttachmentException
	 */
	public ActionForward add(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws InstructionAttachmentException{
		InstructionAttachmentForm form = null;
		InstructionAttachmentView view = null;		
		InstructionPurchaseDetailView ipdView = null;
		
		InstructionAttachmentService service = null;
		InstructionPurchaseDetailService ipdService = null;
		
		HttpSession session = null;		
		String messageError = null;		
		FormFile formFile = null;
		String path = null;				
		
		form = (InstructionAttachmentForm)actionForm;
		service = new InstructionAttachmentService();
		ipdService = new InstructionPurchaseDetailService();
		messageResources = getResources(request);
		session = request.getSession();
		
		try {
			view = form.getView();
			formFile = view.getFile();
			view.setPurchaseInstructionDetailId(NumberUtil.getInt(session.getAttribute(PID_PARAM)));
			//Validar la vista
			validate(view);
			
			//FIXME EL NUMERO DE PADDING CUANTOS SON?
			ipdView = ipdService.getById(view.getPurchaseInstructionDetailId());

			//Armar el path completo
			path = service.buildPath(ipdView,formFile.getFileName());
			
			view.setPath(path);
			
			//Guardar el archivo en una ruta especifica
			service.saveFileToPath(path, formFile);
			
			//Guardar los datos del archivo en la base de datos
			service.addInstructionAttachmentView(view);
			messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), SUCCESS_ADD_LABEL);
			session.setAttribute(MESSAGE, messageError);
		}catch(InstructionAttachmentException ife){
			String arg = null;
			if( ife.getErrorCode().equals("label.instructionattachment.invalidextension") ){
				arg = SystemParameterCollection.getInstance().getSystemParameterBean("ALLOWED_FILE_EXTENSIONS").getValue();
			}else if( ife.getErrorCode().equals("label.instructionattachment.fileziseover") ){
				arg = (SystemParameterCollection.getInstance().getSystemParameterBean("FILE_SIZE_LIMIT").getIntValue()/1024) + "KB";
			}else if( ife.getErrorCode().equals("label.instructionattachment.directoryerror") ){
				arg = SystemParameterCollection.getInstance().getSystemParameterBean("PATH_LOCATION_FOR_FILES").getValue();
			}
			messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), ife.getErrorCode(), arg);
			if(null == messageError){
				InstructionAttachmentException ifee = new InstructionAttachmentException(ife, InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);
				session.setAttribute(CUSTOM_EXCEPTION, ifee);
				form.reset(mapping, request);
				throw ifee;
			}else{
				session.setAttribute( ERROR_MESSAGE, messageError );				
			}
		} catch(Exception e){
			InstructionAttachmentException ppe = new InstructionAttachmentException(e , InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);;			
			session.setAttribute(CUSTOM_EXCEPTION, ppe);
			
			e.printStackTrace(System.out);
			
			throw ppe;
		}		
		
		return mapping.findForward(DEFAULT_FORWARD);
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws InstructionAttachmentException{
		InstructionAttachmentForm form = null;
		InstructionAttachmentView view = null;
		InstructionAttachmentService service = null;
		String attIdParam = null;
		int attId = 0;
		form = (InstructionAttachmentForm)actionForm;
		service = new InstructionAttachmentService();
		attIdParam = request.getParameter("attId");
		if(attIdParam!=null){
			attId = NumberUtil.parseInt(attIdParam);
			view = service.getInstructionAttachmentById(attId);
			form.setView(view);
		}		
		return mapping.findForward(DEFAULT_FORWARD);
	}
	
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionAttachmentException
	 */
	public ActionForward update(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws InstructionAttachmentException{
		InstructionAttachmentForm form = null;
		InstructionAttachmentView view = null;
		InstructionAttachmentService service = null;
		HttpSession session = null;		
		String messageError = null;
		
		form = (InstructionAttachmentForm)actionForm;
		messageResources = getResources(request);
		session = request.getSession(true);
		service = new InstructionAttachmentService();
		try {
			view = form.getView();
			service.updateInstructionAttachmentView(view);
		}catch(InstructionAttachmentException ife){
			String arg = null;
			if( ife.getErrorCode().equals("label.instructionattachment.invalidextension") ){
				arg = SystemParameterCollection.getInstance().getSystemParameterBean("ALLOWED_FILE_EXTENSIONS").getValue();
			}else if( ife.getErrorCode().equals("label.instructionattachment.fileziseover") ){
				arg = SystemParameterCollection.getInstance().getSystemParameterBean("FILE_SIZE_LIMIT").getValue();
			}else if( ife.getErrorCode().equals("label.instructionattachment.directoryerror") ){
				arg = SystemParameterCollection.getInstance().getSystemParameterBean("PATH_LOCATION_FOR_FILES").getValue();
			}
			messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), ife.getErrorCode(), arg);
			if(null == messageError){
				InstructionAttachmentException ifee = new InstructionAttachmentException(ife, InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);
				session.setAttribute(CUSTOM_EXCEPTION, ifee);
				form.reset(mapping, request);
				throw ifee;
			}else{
				session.setAttribute(ERROR_MESSAGE, messageError);				
			}
		} catch(Exception e){
			InstructionAttachmentException ppe = new InstructionAttachmentException(e , InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);;			
			session.setAttribute(CUSTOM_EXCEPTION, ppe);
			
			e.printStackTrace(System.out);
			
			throw ppe;
		}		
		
		return mapping.findForward(DEFAULT_FORWARD);
	}
	
	/**
	 * Validar la vista
	 * @param view
	 * @throws InstructionAttachmentException
	 */
	private void validate(InstructionAttachmentView view) throws InstructionAttachmentException{
		int allowedFileSize = SystemParameterCollection.getInstance().getSystemParameterBean("FILE_SIZE_LIMIT").getIntValue();
		int fileSize = 0;
		String fileExtension = null;
		if(view.getFile()==null){
			throw new InstructionAttachmentException("label.instructionattachment.invalidextension",InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);
		}
		fileExtension = FileExtensionUtils.getFileExtension(view.getFile().getFileName());		
		if(!FileExtensionUtils.isValidExtension(fileExtension)){
			throw new InstructionAttachmentException("label.instructionattachment.invalidextension",InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);
		}else{
			view.setFileExtension(fileExtension);
		}
		fileSize = view.getFile().getFileSize();
		if(fileSize > allowedFileSize){
			throw new InstructionAttachmentException("label.instructionattachment.fileziseover",InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_LISTS);
		}
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws InstructionAttachmentException{
		InstructionAttachmentForm form = null;		
		InstructionAttachmentService service = null;
		HttpSession session = null;		
		String messageError = null;
		String attIdParam = null;
		int attId = 0;
		
		form = (InstructionAttachmentForm)actionForm;
		messageResources = getResources(request);
		session = request.getSession(true);
		service = new InstructionAttachmentService();
		try {
			attIdParam = request.getParameter("attId");
			if(attIdParam!=null){
				attId = NumberUtil.parseInt(attIdParam);
				service.deleteInstructionAttachmentView(attId);
				messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), SUCCESS_DELETE_LABEL);
				session.setAttribute(MESSAGE, messageError);
			}
		}catch(InstructionAttachmentException ife){
			messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), ife.getErrorCode());
			
			if(null == messageError){
				InstructionAttachmentException ifee = new InstructionAttachmentException(ife, InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_DELETE);
				session.setAttribute(CUSTOM_EXCEPTION, ifee);
				form.reset(mapping, request);
				throw ifee;
			}else{
				session.setAttribute(ERROR_MESSAGE, messageError);				
			}
		} catch(Exception e){
			InstructionAttachmentException ppe = new InstructionAttachmentException(e , InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_DELETE);;			
			session.setAttribute(CUSTOM_EXCEPTION, ppe);
			
			e.printStackTrace(System.out);
			
			throw ppe;
		}		
		
		return mapping.findForward(DEFAULT_FORWARD);
	}
	/**
	 * Accion que exporta el archivo excel
	 * 
	 * @author Edgar Joao
	 * @param argMapping
	 * @param argForm
	 * @param argRequest
	 * @param argResponse
	 * @return
	 * @throws Exception
	 */
	public ActionForward exportExcelFile(ActionMapping argMapping, ActionForm argForm,
			HttpServletRequest argRequest, HttpServletResponse argResponse)
			throws Exception {		
		
		HttpSession session = null;		
		String messageError = null;				
		StringBuffer filePath = null;
		String fileName = null;					
		
		session = argRequest.getSession();
		filePath = new StringBuffer(ATTACHMENT_FILE_NAME);			
		fileName = (String) argRequest.getParameter(EXCEL_FILE);
				
		filePath.append(StringUtils.getFileName(fileName));
		filePath.append("\"");
		int read = 0;
		byte[] bytes = new byte[1024];
		
		try{
			if(fileName != null){
				argResponse.setContentType(InstructionAttachmentView.APPLICATION_CONTENT_TYPE_EXCEL_FILE);
				argResponse.setHeader( InstructionAttachmentView.CONTENT_DISPOSITION , filePath.toString() );
							
				OutputStream os = argResponse.getOutputStream();
		    	File file = new File(fileName);
		    	FileInputStream fis = new FileInputStream(file);		    
		    	while((read = fis.read(bytes))!=-1){
		    		os.write(bytes,0,read);
		    	}	    		    		    	
		    	os.flush();
		    	os.close();
		    	fis.close();
			}else{
				messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), FILE_NOT_FOUND);
				session.setAttribute(MESSAGE, messageError);
			}
		} catch(Exception e){
			InstructionAttachmentException ppe = new InstructionAttachmentException(e , InstructionAttachmentException.LAYER_ACTION, InstructionAttachmentException.ACTION_DELETE);;			
			session.setAttribute(CUSTOM_EXCEPTION, ppe);			
			e.printStackTrace(System.out);			
			throw ppe;
		}		
		return argMapping.findForward(DEFAULT_FORWARD);
	}
	
}
